package com.maggroup.conference_system.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.maggroup.conference_system.common.utils.HanLPUtil;
import com.maggroup.conference_system.entity.Question;
import com.maggroup.conference_system.repositories.QuestionRepository;
import com.maggroup.conference_system.service.TextAnalyzeService;


@Service
public class TextAnalyzeServiceImpl implements TextAnalyzeService {
	
	@Autowired
	private QuestionRepository questionRepository;

	@Override
	public List<String> getHotWords(Integer meetingId) {
		List<String> contens = questionRepository.findByMeetingIdAndOverlook(meetingId,Boolean.FALSE).
				stream().map(Question::getContent).collect(Collectors.toList());
		Map<String, Integer> wordMap = new HashMap<String, Integer>();
		for(String content : contens) {
			List<String> segment = HanLPUtil.segment(content);
			if(segment!=null) {
				for(String wordItem : segment) {
					if(wordMap.get(wordItem) == null) {
						wordMap.put(wordItem, 1);
					}else {
						wordMap.put(wordItem, wordMap.get(wordItem)+1);
					}
				}
			}
		}
		
		//top 5
		Set<Entry<String, Integer>> entrySet = wordMap.entrySet();
		ArrayList<Map.Entry<String, Integer>> arrayList = new ArrayList<Map.Entry<String, Integer>>(entrySet);
		Collections.sort(arrayList,new Comparator<Map.Entry<String, Integer>>() {

			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				int compare = o1.getValue().compareTo(o2.getValue());
				return -compare;
			}
		});
		
		List<String> maxString = new ArrayList<>();
		int i=0;
		for(Map.Entry<String, Integer> entry : arrayList) {
			i++;
			if(i>5) {
				break;
			}
			maxString.add(entry.getKey());
		}
		
		return maxString;
	}
   
}
